from rest_framework import viewsets, status
from rest_framework.decorators import action
from rest_framework.response import Response
from django.db import transaction
from .models import Template
from taskblock.models import TaskBlock
from .serializers import (
    TemplateSerializer, 
    TemplateCreateUpdateSerializer, 
    TemplateListSerializer
)
import json


class TemplateViewSet(viewsets.ModelViewSet):
    """
    模板配置视图集
    提供模板的CRUD操作
    """
    queryset = Template.objects.all()
    
    def get_serializer_class(self):
        """根据不同的操作返回不同的序列化器"""
        if self.action == 'list':
            return TemplateListSerializer
        elif self.action in ['create', 'update', 'partial_update']:
            return TemplateCreateUpdateSerializer
        else:
            return TemplateSerializer
    
    def list(self, request, *args, **kwargs):
        """获取模板列表"""
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response({
            'success': True,
            'data': serializer.data,
            'message': '获取模板列表成功'
        })
    
    def retrieve(self, request, *args, **kwargs):
        """获取单个模板详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        
        return Response({
            'success': True,
            'data': serializer.data,
            'message': '获取模板详情成功'
        })
    
    @transaction.atomic
    def create(self, request, *args, **kwargs):
        """创建新模板"""
        serializer = self.get_serializer(data=request.data)
        if serializer.is_valid():
            template = serializer.save()
            
            # 返回创建的模板详情
            detail_serializer = TemplateSerializer(template)
            return Response({
                'success': True,
                'data': detail_serializer.data,
                'message': '模板创建成功'
            }, status=status.HTTP_201_CREATED)
        else:
            return Response({
                'success': False,
                'errors': serializer.errors,
                'message': '模板创建失败'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    @transaction.atomic
    def update(self, request, *args, **kwargs):
        """更新模板"""
        partial = kwargs.pop('partial', False)
        instance = self.get_object()
        serializer = self.get_serializer(instance, data=request.data, partial=partial)
        
        if serializer.is_valid():
            template = serializer.save()
            
            # 返回更新后的模板详情
            detail_serializer = TemplateSerializer(template)
            return Response({
                'success': True,
                'data': detail_serializer.data,
                'message': '模板更新成功'
            })
        else:
            return Response({
                'success': False,
                'errors': serializer.errors,
                'message': '模板更新失败'
            }, status=status.HTTP_400_BAD_REQUEST)
    
    def destroy(self, request, *args, **kwargs):
        """删除模板"""
        instance = self.get_object()
        template_name = instance.name
        instance.delete()
        
        return Response({
            'success': True,
            'message': f'模板 "{template_name}" 删除成功'
        }, status=status.HTTP_204_NO_CONTENT)
    
    @action(detail=True, methods=['post'])
    def copy(self, request, pk=None):
        """复制模板"""
        original_template = self.get_object()
        
        # 生成新的模板名称
        template_count = Template.objects.count()
        new_name = f"模板{template_count + 1}"
        
        with transaction.atomic():
            # 创建新模板，包含原模板的任务块布局数据
            new_template = Template.objects.create(
                name=new_name,
                description=f"复制自 {original_template.name}",
                task_blocks_layout=original_template.task_blocks_layout
            )
        
        # 返回新创建的模板
        serializer = TemplateSerializer(new_template)
        return Response({
            'success': True,
            'data': serializer.data,
            'message': f'模板复制成功，新模板名称: {new_name}'
        }, status=status.HTTP_201_CREATED)
    
    @action(detail=False, methods=['post'])
    def reorder_names(self, request):
        """重新整理模板名称"""
        templates = Template.objects.all().order_by('id')
        
        with transaction.atomic():
            for index, template in enumerate(templates):
                template.name = f"模板{index + 1}"
                template.save()
        
        return Response({
            'success': True,
            'message': '模板名称重新整理完成'
        })
    
    @action(detail=True, methods=['post'])
    def import_taskblocks(self, request, pk=None):
        """从TaskBlock表导入任务块到模板的任务块排列区"""
        template = self.get_object()
        taskblock_ids = request.data.get('taskblock_ids', [])
        
        if not taskblock_ids:
            return Response({
                'success': False,
                'message': '请提供要导入的任务块ID列表'
            }, status=status.HTTP_400_BAD_REQUEST)
        
        try:
            # 获取指定的任务块
            taskblocks = TaskBlock.objects.filter(id__in=taskblock_ids)
            
            # 构建任务块布局数据
            task_blocks_layout = []
            for taskblock in taskblocks:
                # 根据任务块状态设置颜色
                color_map = {
                    'active': '#87CEEB',      # 天蓝色
                    'inactive': '#D3D3D3',    # 浅灰色
                    'completed': '#90EE90',   # 浅绿色
                    'paused': '#FFB6C1'       # 浅粉色
                }
                
                task_block_data = {
                    'id': taskblock.id,
                    'name': taskblock.task_name,
                    'duration': taskblock.duration,
                    'color': color_map.get(taskblock.status, '#87CEEB'),
                    'requiredDevice': taskblock.required_device.device_name if taskblock.required_device else '',
                    'status': taskblock.status,
                    'daily_device_config': taskblock.daily_device_config
                }
                task_blocks_layout.append(task_block_data)
            
            # 更新模板的任务块布局
            template.task_blocks_layout = task_blocks_layout
            template.save()
            
            return Response({
                'success': True,
                'data': TemplateSerializer(template).data,
                'message': f'成功导入{len(task_blocks_layout)}个任务块到模板'
            })
            
        except Exception as e:
            return Response({
                'success': False,
                'message': f'导入任务块失败: {str(e)}'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
    
    @action(detail=False, methods=['get'])
    def available_taskblocks(self, request):
        """获取可用的任务块列表"""
        # 按照数据库ID顺序获取任务块，确保顺序一致
        taskblocks = TaskBlock.objects.all().order_by('id')
        
        # 构建任务块数据
        taskblocks_data = []
        for taskblock in taskblocks:
            # 从daily_device_config中提取设备信息
            required_device = None
            if taskblock.daily_device_config:
                try:
                    config_data = json.loads(taskblock.daily_device_config)
                    devices = config_data.get('devices', [])
                    if devices and len(devices) > 0:
                        required_device = ', '.join(devices)  # 如果有多个设备，用逗号分隔
                except (json.JSONDecodeError, TypeError):
                    pass
            
            # 如果daily_device_config中没有设备信息，尝试从required_device字段获取
            if not required_device and taskblock.required_device:
                required_device = taskblock.required_device.device_name
                
            taskblock_data = {
                'id': taskblock.id,
                'name': taskblock.task_name,
                'duration': taskblock.duration,
                'color': '#87CEEB',  # 统一设置为天蓝色
                'requiredDevice': required_device,
                'status': taskblock.status,
                'daily_device_config': taskblock.daily_device_config
            }
            taskblocks_data.append(taskblock_data)
        
        return Response({
            'success': True,
            'data': taskblocks_data,
            'message': '获取可用任务块列表成功'
        })
